package com.neuedu.helloworld;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.neuedu.helloworld.concat.ConcatEditActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class ConcatActivity extends AppCompatActivity {

    private ListView  lvConcatList;

    private List<Map<String,Object>>  lvConcatData = new ArrayList<>();
//    private ArrayAdapter adapter = null;
    String[] concatNames = {"张飞","刘备","诸葛亮","孙权","孙尚香","黄月英1"};
    String[] concatTypes = {"成人","学生","老人"};

    SimpleAdapter adapter = null;



//    private void initData(){
//        Random rnd = new Random();
//        for (int i = 0; i < concatNames.length; i++) {
//            String concatName = concatNames[i];
//            HashMap person = new HashMap();
//            person.put("id", i);
//            person.put("concatType", concatTypes[rnd.nextInt(3)]);
//            person.put("concatName", concatName + "(" + person.get("concatType") + ")");
//            person.put("concatIdNo", "身份证:" + Math.abs(rnd.nextLong()));
//            person.put("concatPhone", "电话:" + System.currentTimeMillis() +i);
//            lvConcatData.add(person);
//        }
//
//    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_concat);
        lvConcatList = findViewById(R.id.lvConcatList);
        setTitle("我的联系人");
        lvConcatList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HashMap<String, Object> person = (HashMap<String, Object>) lvConcatData.get(position);


                Intent intent= new Intent(ConcatActivity.this ,  ConcatEditActivity.class);

                //携带数据
                intent.putExtra("personData",person);
               // startActivity(intent);

                //打开Activity需要结果
                startActivityForResult(intent,100);

            }
        });


        String[] from = {"concatName","concatIdNo","concatPhone"}; //从List<Map> 集合    从某一行的Map 的哪个key  取数据
        int[] to = {R.id.concatName,R.id.concatIdNo,R.id.concatPhone};  // 设置到单行布局容器的组件
        adapter = new SimpleAdapter(this,lvConcatData   ,R.layout.activity_concat_item ,from,to   );


        lvConcatList.setAdapter(adapter);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
       int id =  data.getIntExtra("id",-1);

       if(id != -1){

           Toast.makeText(this, "被删除的ID"+id, Toast.LENGTH_SHORT).show();

           //根据ID， 删除对应的数据（ListView）

           int index = id;
           lvConcatData.remove(index); //只能删一次

           //重新渲染
           adapter.notifyDataSetChanged();

       }
    }


    @Override
    protected void onResume() {
        super.onResume();

        //加载联系人

        new LoadConcatListTask().execute();

    }





    class LoadConcatListTask extends AsyncTask<String,Object , List<Map<String, Object>> >{

        private ProgressDialog process;

        //预处理的任务
        @Override
        protected void onPreExecute() {

            //打开  loading
            process = ProgressDialog.show(ConcatActivity.this, "提示", "加载中，请稍后", false, false);

        }



        @Override
        protected List<Map<String, Object>> doInBackground(String... strings) {

            try {
                URL url = new URL(AndroidConstants.HOST+"/concat/list");
                URLConnection connection = url.openConnection();


                InputStream inputStream = connection.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));


                Gson gson = new GsonBuilder().create();
//                HashMap map = gson.fromJson(br, HashMap.class);

                ArrayList concatList = gson.fromJson(br, new TypeToken<ArrayList<HashMap>>() {  }.getType());


                return concatList;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;

        }


        //请求响应回来的时候 执行
        //MainThread
        @Override
        protected void onPostExecute(List<Map<String, Object>> list) {

            process.dismiss();

            Log.d("Concat",list.toString());
            Log.d("Concat",list.toString());
            Log.d("Concat",list.toString());
            Log.d("Concat",list.toString());
            Log.d("Concat",list.toString());
            Log.d("Concat",list.toString());
            Log.d("Concat",list.toString());
            Log.d("Concat",list.toString());

            //将数据更新到  ListView 对应的  data
            //    private List<HashMap<String,Object>>  lvConcatData = new ArrayList<>();

//            List<Map<String, Object>>


            lvConcatData.addAll(list) ;
            //通过  适配器 ，通知 ListView 重新渲染
            adapter.notifyDataSetChanged();

        }
    }





}